<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\Manage\controller;

use app\common\controller\Manage;
use app\common\model\User as UserModel;
use app\common\model\Dorm as DormModel;
use app\common\model\Dept as DeptModel;
use app\common\model\DormUserRel as DormUserRelModel;
use app\common\model\EntrustUserRel as EntrustUserRel;
use app\common\model\Common;
use think\facade\Request;
use think\Db;
use think\facade\Log;

class Apartment extends Manage
{

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function dorm()
    {
        if(Request::isAjax())
        {
            $dormModel = new DormModel();
            return $dormModel->tableData(input('param.'));
        }
        return $this->fetch('dorm');
    }


    /**
     *  宿舍添加
     * @return array|mixed
     */
    public function dormAdd()
    {
        $this->view->engine->layout(false);
        if(Request::isPost())
        {
            $DormModel = new DormModel();
            return $DormModel->addData(input('param.'));
        }
        return $this->fetch('dormAdd');
    }


    /**
     *  宿舍修改
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function dormEdit()
    {
        $this->view->engine->layout(false);
        $DormModel = new DormModel();
        if(Request::isPost())
        {
            return $DormModel->saveData(input('param.'));
        }
        $data = $DormModel->where('id',input('param.id/d'))->find();
        if (!$data) {
            return error_code(10002);
        }
        return $this->fetch('dormEdit',['data' => $data]);
    }

    public function dormMgr()
    {
        if(Request::isAjax())
        {
            $dormModel = new DormUserRelModel();
            return $dormModel->tableData(input('param.')); 
        }
        return $this->fetch('dormMgr');
    }
    
    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function dormUser()
    {
        $this->view->engine->layout(false);

        $dormModel = new DormModel();
        $dormList = $dormModel->order('sort asc')->select();
 
        $dormData = [];
        foreach($dormList as $v){
            $dormData[] = $v;
        }

        return $this->fetch('dormUser', ['dormData' => $dormData]);
    }

    public function getMgrInfo()
    {
        $userModel = new UserModel();
        $userList = $userModel->getDormMgrInfo();
  
        $result = [
            'status' => true,
            'msg' => '获取成功',
            'data' => $userList
        ];

        return $result;
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function getdormUserInfo()
    { 
        $dormModel = new DormUserRelModel();
        return $dormModel->tableData(input('param.')); 
    }

    /**
     *  宿舍管理员 添加
     * @return array|mixed
     */
    public function dormUserAdd()
    {
        $dormModel = new DormUserRelModel();
        return $dormModel->addData(input('param.'));
    }
 
    /**
     *  宿舍管理员 软删除
     * User:tony
     * @return array
     */
    public function dormUserDel()
    {
        $result = ['status'=>true, 'msg'=>'删除成功','data'=>''];

        // 判断有没有委托关系，如果有则不能删除
        $entrustUserRel = new EntrustUserRel();
        
        // 判断是否一个人被多人委托
        $info = $entrustUserRel->field('truename')
            ->alias('r')
            ->join('user u', 'u.mobile = r.userMobile')
            ->where(['entrustUserMobile'=>input('param.mobile/s')])->find();

        if($info){
            $result['status'] = false;
            $result['msg'] = '该用户已被' . $info['truename'] . '委托，需要先解除委托关系';
            return $result;
        }

        // 如果已经委托人员也不能被添加为被委托人
        $infoExist = $entrustUserRel->where(['userMobile'=>input('param.mobile/s')])->find();
        if($infoExist){
            $result['status'] = false;
            $result['msg'] = '该用户是委托人了，需要先解除委托关系！';   
            return $result;
        }

        $dormModel = new DormUserRelModel();
        if (!$dormModel->where('mobile',input('param.mobile/s'))->delete()) {
            $result['status'] = false;
            $result['msg'] = '删除失败';
        }

        return $result;
    }

    public function entrust()
    {
        if(Request::isAjax())
        {
            $post = input('param.');
            
            // 没有实体的model暂时这么处理。
            if(isset($post['limit'])){
                $limit = $post['limit'];
            }else{
                $limit = config('paginate.list_rows');
            }
    
            $page = input('page', 0);
            $index = ($page - 1) * $limit;

            $idsString = ''; 
            if(isset($post['pid']) && $post['pid'] != ""){
                $deptModel = new DeptModel();
                $ids = $deptModel->api_getAllDeptIds($post['pid']);
                
                foreach($ids as $val) {
                    $idsString .= ',' . $val;
                }
                
                if (substr($idsString, 0, 1) == ',') {
                    $idsString = substr($idsString, 1);
                }
            } 

            $model = new Common();
            $list = $model->query("call getEntrustInfo('".$idsString."','".$post['mobile']."','".$post['truename']."','".$post['assistant_mobile']."','".$post['assistant_truename']."',".$index.",".$limit.");");
            
            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list[1]);
            $re['data'] = $list[0];

            return $re;
        }
        return $this->fetch('entrust');
    }
    
    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function entrustUser()
    {
        $this->view->engine->layout(false);
 
        // 这里要排除掉已经是委托的成员
        $userModel = new UserModel();
        $list = $userModel->getApartmentTeacherList();
        $this->assign('userList', $list);
        
        return $this->fetch('entrustUser'); 
    }

    /**
     *  委托
     * User:tony
     * @return array|mixed
     */
    public function getEntrustInfo()
    { 
        $userModel = new UserModel();
        $userList = $userModel->getEntrustInfo(input('param.'));
             
        $result = [
            'status' => true,
            'msg' => '获取成功',
            'data' => $userList
        ];

        return $result;
    }

    /**
     *  助手
     * User:tony
     * @return array|mixed
     */
    public function getEntrustList()
    { 
        $entrustUserRel = new EntrustUserRel();
        return $entrustUserRel->tableData(input('param.')); 
    }

    /**
     *  委托 添加
     * User:tony
     * @return array|mixed
     */
    public function entrustUserAdd()
    {
        $entrustUserRel = new EntrustUserRel();
        return $entrustUserRel->addData(input('param.'));
    }
 
    /**
     *  委托 软删除
     * User:tony
     * @return array
     */
    public function entrustUserDel()
    {
        $result = ['status'=>true, 'msg'=>'删除成功','data'=>''];

        $entrustUserRel = new EntrustUserRel();
        if (!$entrustUserRel->where('entrustUserMobile',input('param.entrustUserMobile/s'))->delete()) {
            $result['status'] = false;
            $result['msg'] = '删除失败';
        }

        return $result;
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function statisticsByCollege(){
        if(Request::isAjax())
        {
            // 获取最近10条数据
            $userModel = new UserModel();
            $list = $userModel->query('call statisticsByCollege;');
            
            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list[0]);
            $re['data'] = $list[0];
            return $re;
        }
        return $this->fetch('statisticsByCollege');
    }
    
    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function statisticsByDorm(){
        if(Request::isAjax())
        {
            // 获取最近10条数据
            $userModel = new UserModel();
            $list = $userModel->query('call statisticsByDorm;');
            
            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list[0]);
            $re['data'] = $list[0];
            return $re;
        }
        return $this->fetch('statisticsByDorm');
    }
    
    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function statisticsByTeacher(){
        
        if(Request::isAjax())
        {
            $collegeName = input('collegeName');
            $teacherName = input('teacherName');
            // 获取最近10条数据
            $userModel = new UserModel();
            $list = $userModel->query("call statisticsByTeacher('".$collegeName."', '".$teacherName."');");
            
            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list['0']);
            $re['data'] = $list['0'];
            return $re;
        }
        return $this->fetch('statisticsByTeacher');
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function apartmentdetail(){
        if(Request::isAjax())
        {
            // 参数解析
            $collegeName = input('collegeName');
            $dormName = input('dormName');
            $teacherName = input('teacherName');
            $xh = input('xh');
            $xm = input('xm');
            $theDate = explode(' 到 ',input('param.date'));
            $limit = input('limit', 0); 
            $page = input('page', 0);
            $index = ($page - 1) * $limit;

            if(count($theDate)!=2){
                $re['code'] = 0;
                $re['msg'] = '';
                $re['count'] = 0;
                $re['data'] = [];
                return $re;
            }

            $beginDate = strtotime($theDate[0]);
            $endDate = strtotime($theDate[1])+60*60*24;

            // 这里直接调用SQL查询数据
            $userModel = new UserModel();
            $list = $userModel->query("call apartmentDetail('".$collegeName."','".$dormName."','".$teacherName."','".$xh."','".$xm."','".$beginDate."','".$endDate."',".$index.",".$limit.");");
            
            if(count($list) == 0){
                $re['code'] = 0;
                $re['msg'] = '';
                $re['count'] = 0;
                $re['data'] = [];
                return $re;
            }

            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list[1]);
            $re['data'] = $list[0];
            return $re; 
        }
        return $this->fetch('apartmentdetail');
    }

    // 发放记录删除
    public function apartmentDetailDel()
    {       
        $id = input('param.')['id'];
        
        // 这里直接调用SQL查询数据
        $userModel = new UserModel();
        $userModel->query("call apartmentDetaildel('".$id."');");
        
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );

        return $return_data;
    }
    
}